
import urllib.request
import random


# 网页地址
url = 'http://www.baidu.com/s?wd=ip'

# 请求头
headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
    }

# 请求对象的定制
request = urllib.request.Request(url=url, headers=headers)

# 高密ip
proxies_pool = [
    {'http': '121.230.211.142:3256111'},
    {'http': '121.230.211.142:3256222'},
]
# 随机
proxies = random.choice(proxies_pool)
# print(proxies)

# 代理不可以直接使用
# 步骤1
handler = urllib.request.ProxyHandler(proxies=proxies)

# 步骤2
build_opener = urllib.request.build_opener(handler)

# 步骤3
# 模拟浏览器向服务器发送请求
response = build_opener.open(request)

# 接收服务器响应的信息
content = response.read().decode('utf-8')
# print(content)

# 保存信息
with open('daili2.html', 'w', encoding='utf-8') as fp:
    fp.write(content)
